# pay.py
from fastapi import APIRouter, Request, Depends
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
from database import get_db
from models import Users, UserType, Orders, Kami, OrderStatus, ActivationMethod
from alipay import AliPay
import uuid
from utils import alipay_sdk, wechat_sdk

router = APIRouter(tags=["支付模块"], prefix="/pay")

# 套餐配置
VIP_PLANS = {
    "1": {"vip_type": "month", "days": 30, "price": 0.15},
    "2": {"vip_type": "season", "days": 180, "price": 79.9},
    "3": {"vip_type": "year", "days": 365, "price": 0.02}
}


# ----------------- 创建订单 -----------------
@router.post("/index")
def pay_index(request: Request, payload: dict, db: Session = Depends(get_db)):
    """
    payload: {"id": "1", "paytype": "alipaydmf"}
    """
    user_id = request.session.get("user_id")
    if not user_id:
        return {"status": 401, "msg": "请先登录"}

    user = db.query(Users).filter(Users.user_id == user_id).first()
    if not user:
        return {"status": 404, "msg": "用户不存在"}

    plan_id = str(payload.get("id"))
    pay_type = payload.get("paytype")
    if plan_id not in VIP_PLANS:
        return {"status": 400, "msg": "错误的套餐ID"}

    plan = VIP_PLANS[plan_id]

    # 生成唯一订单号
    out_trade_no = str(uuid.uuid4().hex)[:20]

    # 创建数据库订单
    order = Orders(
        user_id=user.user_id,
        vip_type=UserType(plan["vip_type"]),
        pay_type=pay_type,
        amount=plan["price"],
        order_id=out_trade_no,
        status=OrderStatus.pending
    )
    db.add(order)
    db.commit()
    db.refresh(order)

    # 根据支付方式调用不同的 SDK
    qr_code = None
    if pay_type == "alipay":
        try:
            qr_code = alipay_sdk.alipay_trade_precreate(out_trade_no, plan["price"], f"{plan['vip_type']}会员")
        except Exception as e:
            return {"status": 500, "msg": f"支付宝接口异常: {str(e)}"}

    elif pay_type == "wxpay":
        try:
            qr_code = wechat_sdk.wechat_native_pay(out_trade_no, plan["price"], f"{plan['vip_type']}会员")
        except Exception as e:
            return {"status": 500, "msg": f"微信下单失败: {e}"}

    elif pay_type == "other":
        # 你以后想接入 PayPal、Stripe，在这里扩展
        return {"status": 400, "msg": "暂不支持该支付方式"}

    else:
        return {"status": 400, "msg": "不支持的支付方式"}

    if not qr_code:
        return {"status": 500, "msg": "生成支付二维码失败"}

    return {
        "status": 100,
        "msg": "订单创建成功",
        "orderid": out_trade_no,
        "price": plan["price"],
        "qr_code": qr_code
    }


# ----------------- 支付状态轮询 -----------------
@router.post("/payquery")
def pay_query(payload: dict, db: Session = Depends(get_db)):
    """
    payload: {"outTradeNo": "xxx"}
    统一轮询接口，根据订单 pay_type 调用对应支付查询
    """
    out_trade_no = payload.get("outTradeNo")
    if not out_trade_no:
        return {"status": 400, "msg": "缺少订单号"}

    # --------------------------
    # 步骤1：查询订单 + 超时判断
    # --------------------------
    try:
        order = db.query(Orders).filter(Orders.order_id == out_trade_no).first()
        if not order:
            return {"status": 404, "msg": "订单不存在"}

        # 1. 计算超时时间（当前时间 - 15分钟 = 超时阈值）
        timeout_threshold = datetime.now() - timedelta(minutes=1)

        print("创建时间", order.created_at-timeout_threshold)
        print("order.status", order.status.value)


        # 订单已超时且未支付 → 返回超时状态
        if order.status.value == "pending" and order.created_at < timeout_threshold:
            # 更新订单状态为“支付失败”，避免后续重复判断
            order.status = OrderStatus.expired
            db.commit()
            print(f"订单超时未支付，已取消 | out_trade_no={out_trade_no} | 超时时间={timeout_threshold}")
            return {"status": 103, "msg": "支付已超时，请重新发起支付"}

        # 订单已支付/已取消 → 直接返回对应状态，停止轮询
        # 假设你的订单状态字段是order_status，已支付值为"paid"
        if order.status.value == "paid":
            print(f"订单已支付，无需重复查询 | out_trade_no={out_trade_no} | pay_type={order.pay_type}")
            return {"status": 102, "msg": "支付成功"}

        if order.status.value == "expired":
            return {"status": 103, "msg": "订单已取消，请重新发起支付"}

    except Exception as e:
        # 数据库查询异常：单独捕获，日志记录详细信息
        print(f"订单查询数据库异常 | out_trade_no={out_trade_no} | 错误信息: {str(e)}")
        return {"status": 400, "msg": f"订单查询失败: {str(e)}"}

    # --------------------------
    # 步骤2：未超时 → 正常调用支付SDK查询
    # --------------------------
    try:
        if order.pay_type == "alipay":
            print(f"开始支付宝支付轮询 | out_trade_no={out_trade_no}")
            # ----------------- 支付宝查询 -----------------
            result = alipay_sdk.alipay_client.api_alipay_trade_query(out_trade_no=out_trade_no)

            # 接口调用成功，判断支付状态
            trade_status = result.get("trade_status")
            if trade_status == "TRADE_SUCCESS":
                update_order_and_user(order, db, method="alipay")
                return {"status": 102, "msg": "支付成功"}
            elif trade_status in ["WAIT_BUYER_PAY", "TRADE_CLOSED"]:
                print(f"支付宝未支付 | out_trade_no={out_trade_no} | trade_status={trade_status}")
                return {"status": 101, "msg": "未支付"}
            else:
                return {"status": 101, "msg": "未支付"}

        elif order.pay_type == "wxpay":
            print(f"开始微信支付轮询 | out_trade_no={out_trade_no}")
            # ----------------- 微信查询 -----------------
            result = wechat_sdk.wechat_order_query(out_trade_no)
            if result.get("return_code") == "SUCCESS" and result.get("result_code") == "SUCCESS":
                trade_state = result.get("trade_state")
                if trade_state == "SUCCESS":
                    update_order_and_user(order, db, method="wechat")
                    return {"status": 102, "msg": "支付成功"}

                elif trade_state in ["NOTPAY", "USERPAYING"]:
                    return {"status": 101, "msg": "未支付"}

                else:
                    return {"status": 500, "msg": f"支付失败: {trade_state}"}

            else:
                return {"status": 500, "msg": f"微信接口异常: {result.get('return_msg')}"}

        else:
            return {"status": 400, "msg": f"未知支付类型: {order.pay_type}"}

    except Exception as e:
        return {"status": 500, "msg": f"支付查询异常: {str(e)}"}


def update_order_and_user(order: Orders, db: Session, method: str):
    from datetime import timezone
    now = datetime.now(timezone.utc)

    order.status = OrderStatus.paid
    order.paid_at = now

    user = db.query(Users).filter(Users.user_id == order.user_id).first()

    # 转换 vip_expire 为 aware datetime
    user_expire = user.vip_expire
    if user_expire and user_expire.tzinfo is None:
        user_expire = user_expire.replace(tzinfo=timezone.utc)

    if user.vip_expire is None or user_expire < now or UserType(order.vip_type.value) != UserType.admin:
        user.user_type = UserType(order.vip_type.value)
        user.activated_at = now
        user.vip_status = 1

        add_days = VIP_PLANS[str([k for k, v in VIP_PLANS.items() if v['vip_type'] == order.vip_type.value][0])]["days"]
        if user_expire and user_expire > now:
            user.vip_expire = user_expire + timedelta(days=add_days)
        else:
            user.vip_expire = now + timedelta(days=add_days)

        user.activation_method = ActivationMethod(method)

    db.commit()


@router.post("/kami")
def kami_pay(request: Request, payload: dict, db: Session = Depends(get_db)):
    """
    卡密支付接口
    payload: {"code": "xxxx"}
    """
    user_id = request.session.get("user_id")
    if not user_id:
        return {"status": 401, "msg": "请先登录"}

    user = db.query(Users).filter(Users.user_id == user_id).first()
    if not user:
        return {"status": 404, "msg": "用户不存在"}

    code = payload.get("code")
    if not code:
        return {"status": 400, "msg": "请提供卡密"}

    # 查询卡密是否存在且未使用
    kami_item = db.query(Kami).filter(Kami.code == code, Kami.is_used == 0).first()
    if not kami_item:
        return {"status": 404, "msg": "卡密无效或已使用"}

    try:
        # 标记卡密已使用
        kami_item.is_used = 1
        kami_item.used_at = datetime.now(timezone.utc)
        kami_item.used_by = user.user_id  # 记录使用者
        update_user_kami(user, kami_item, db, method="kami")

        # 创建数据库订单
        order = Orders(
            user_id=user.user_id,
            vip_type=kami_item.vip_type,
            pay_type="kami",
            amount=0,
            order_id=code,
            status=OrderStatus.paid,
            paid_at = kami_item.used_at
        )
        db.add(order)
        db.commit()
        db.refresh(order)


        return {"status": 102, "msg": "卡密激活成功"}
    except Exception as e:
        db.rollback()
        return {"status": 500, "msg": f"卡密支付异常: {str(e)}"}


def update_user_kami(user: Users, kami_item: Kami, db: Session, method: str):
    """
    根据卡密更新用户会员信息
    """
    now = datetime.now(timezone.utc)

    # 转换 vip_expire 为 aware datetime
    user_expire = user.vip_expire
    if user_expire and user_expire.tzinfo is None:
        user_expire = user_expire.replace(tzinfo=timezone.utc)

    user.user_type = UserType(kami_item.vip_type)
    user.activated_at = now
    user.vip_status = 1

    # 计算新的到期时间
    if user_expire and user_expire > now:
        user.vip_expire = user_expire + timedelta(days=kami_item.days)
    else:
        user.vip_expire = now + timedelta(days=kami_item.days)

    user.activation_method = ActivationMethod(method)

    db.commit()
